package com.example.shopping.service;

import com.example.shopping.entity.User;
import com.example.shopping.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserRepository userRepository;


    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public User findByUid(Integer uid) {
        return userRepository.findByUid(uid);
    }

    @Override
    public void deleteUserByUid(int uid) {
        userRepository.deleteById(uid);

    }

    @Override
    public void saveUser(User user) {
        userRepository.save(user);

    }

    @Override
    public User findById(Integer uid) {
        return userRepository.findByUid(uid);
    }

    @Override
    public void updateUser(User user) {
        userRepository.save(user);
    }

    @Override
    public Page<User> findAllUser(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    @Override
    public Page<User> queryUsers(String username, String mailingaddress, String ssex, int pageNo, int pageSize) {

        // 将空字符串转为 null，让 JPA 忽略这个条件
        if (ssex != null && ssex.trim().isEmpty()) {
            ssex = null;
        }

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        return userRepository.findUsersWithDynamicCriteria(username, mailingaddress, ssex, pageable);

    }

    @Override
    public User authenticate(int uid, String password) {
         User u=userRepository.findByUid(uid);


         return u;

    }


}
